import json

import requests

from app import settings
from libs.common import MD5

api_key = 'cf3cfv4i9l7kw2gej'


def app_top_up(cashier_id, order_sn, card_id, username, pay_mode, num):
    err = None
    if pay_mode not in [2, 3, 4, 7]:
        return '无效的支付方式'
    auth_key = MD5(api_key + username) + str(cashier_id)
    data = {
        "cashier": cashier_id,
        "username": username,
        "cardId": card_id,
        "payMode": pay_mode,
        "num": num,
        "token": auth_key,
        "order_sn": order_sn,
    }
    resp = requests.post(settings.API_STORAGE_RECHARGE_URL, json.dumps(data))
    resp_dict = resp.json()
    resp_code = resp_dict.get('code', None)
    if resp_code != 0:
        err = '充值失败'
        print(err, '接口响应：', resp_dict, data)
        msg = resp_dict.get('msg', None)
        if type(msg) is str:
            err = msg
    return err


def app_goods_exchange_coupon(cashier_id, username, cs_order_id):
    err = None
    auth_key = MD5(api_key + username) + str(cashier_id)
    data = {
        "cashier": cashier_id,
        "order_id": cs_order_id,
        "username": username,
        "token": auth_key,
    }
    resp = requests.post(settings.API_GOODS_EXCHANGE_COUPON_URL, json.dumps(data))
    resp_dict = resp.json()
    resp_code = resp_dict.get('code', None)
    if resp_code != 0:
        err = '失败'
        print(err, '接口响应：', resp_dict, data)
        msg = resp_dict.get('msg', None)
        if type(msg) is str:
            err = msg
    return err


def app_deduct_coupon(order_sn, state):
    err = None
    auth_key = MD5(api_key + '')
    data = {
        "state": state,
        "order_id": order_sn,
        "token": auth_key,
    }
    resp = requests.post(settings.API_DEDUCT_COUPON_URL, json.dumps(data))
    resp_dict = resp.json()
    resp_code = resp_dict.get('code', None)
    # resp_msg = resp_dict.get('msg', '')
    if resp_code != 0:
        err = '接口响应失败'
        print(err, resp_dict, data)
        msg = resp_dict.get('msg', None)
        if type(msg) is str:
            err = msg
    return err
